package org.sean.framework.validator;


import org.sean.framework.code.StatusInfo;
import org.sean.framework.exception.StatusException;
import org.sean.framework.validator.group.ADD;
import org.sean.framework.validator.group.DELETE;
import org.sean.framework.validator.group.GET;
import org.sean.framework.validator.group.LIST;
import org.sean.framework.validator.group.UPDATE;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * <pre>
 * hibernate-validator校验工具类
 * 参考文档
 * 官方文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 * 中文文档: https://www.jianshu.com/p/ff0ba92f78bd
 * // @NotBlank(message="用户名不能为空", groups = {Add.class})
 *    private String username;
 * </pre>
 *
 * @author sean.xie
 * @see ADD
 * @see UPDATE
 * @see DELETE
 * @see GET
 * @see LIST
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    private ValidatorUtils() {
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws StatusException 校验不通过，则报StatusException异常
     */
    public static void validate(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new StatusException(StatusInfo.verifyFailed().setAnyMessage(constraint.getMessage()));
        }
    }
}
